package cn.dankal.flyaudio.adapter;

import android.graphics.Color;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.stetho.common.LogUtil;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewAdapter;
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewHolder;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.TimeUtil;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.configs.LiveDataBusConstant;
import cn.dankal.flyaudio.entity.ChatMessageEntity;
import cn.dankal.flyaudio.friend.SortConvList;
import cn.dankal.flyaudio.friend.SortTopConvList;
import cn.dankal.flyaudio.friend.utils.TimeFormat;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.PromptContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.ContentType;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.enums.MessageDirect;
import cn.jpush.im.android.api.enums.MessageStatus;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;

public class ShareFriendAdapter extends BaseRecyclerViewAdapter<Conversation> {
    /**
     * 无选择模式
     */
    public static final int PICK_MODEL_EMPTY = 1001;
    /**
     * 单选模式
     */
    public static final int PICK_MODEL_SINGLE = 1002;
    /**
     * 多选模式
     */
    public static final int PICK_MODEL_MORE = 1003;
    private static final int REFRESH_CONVERSATION_LIST = 0x3003;
    private UIHandler mUIHandler = new UIHandler(this);


    private HashMap<Conversation, Integer> mAtConvMap = new HashMap<>();
    private HashMap<Conversation, Integer> mAtAllConv = new HashMap<>();
    private SparseBooleanArray mArray = new SparseBooleanArray();
    private SparseBooleanArray mAtAll = new SparseBooleanArray();
    private Map<String, String> mDraftMap = new HashMap<>();
    private List<Conversation> selectConv = new ArrayList<>();

    private int pickModel = PICK_MODEL_EMPTY;

    @Override
    protected int getLayoutResId(int viewType) {
        return R.layout.item_share_friend;
    }

    @Override
    protected BaseRecyclerViewHolder getViewHolder(ViewGroup parent, View rootView, int viewType) {
        return new ViewHolder(rootView);
    }

    public void setPickModel(int pickModel) {
        this.pickModel = pickModel;
        notifyDataSetChanged();
    }

    public int getPickModel() {
        return pickModel;
    }

    public List<Conversation> getPickMembers() {
        return selectConv;
    }

    public void setToTop(Conversation conv) {
        int oldCount = 0;
        int newCount = 0;
        //如果是旧的会话
        for (Conversation conversation : getDatas()) {
            if (conv.getId().equals(conversation.getId())) {
                //如果是置顶的,就直接把消息插入,会话在list中的顺序不变
                if (!TextUtils.isEmpty(conv.getExtra())) {
                    mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
                    //这里一定要return掉,要不还会走到for循环之后的方法,就会再次添加会话
                    return;
                    //如果不是置顶的,就在集合中把原来的那条消息移出,然后去掉置顶的消息数量,插入到集合中
                } else {
                    //因为后面要改变排序位置,这里要删除
                    getDatas().remove(conversation);
                    //这里要排序,因为第一次登录有漫游消息.离线消息(其中群组变化也是用这个事件下发的);所以有可能会话的最后一条消息
                    //时间比较早,但是事件下发比较晚,这就导致乱序.所以要重新排序.

                    //排序规则,每一个进来的会话去和倒叙list中的会话比较时间,如果进来的会话的最后一条消息就是最早创建的
                    //那么这个会话自然就是最后一个.所以直接跳出循环,否则就一个个向前比较.
                    for (int i = getDatas().size(); i > SharePreferenceManager.getCancelTopSize(); i--) {
                        if (conv.getLatestMessage() != null && getDatas().get(i - 1).getLatestMessage() != null) {
                            if (conv.getLatestMessage().getCreateTime() > getDatas().get(i - 1).getLatestMessage().getCreateTime()) {
                                oldCount = i - 1;
                            } else {
                                oldCount = i;
                                break;
                            }
                        } else {
                            oldCount = i;
                        }
                    }
                    getDatas().add(oldCount, conv);
                    mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
                    return;
                }
            }
        }
        if (getDatas().size() == 0) {
            getDatas().add(conv);
        } else {
            //如果是新的会话,直接去掉置顶的消息数之后就插入到list中
            for (int i = getDatas().size(); i > SharePreferenceManager.getCancelTopSize(); i--) {
                if (conv.getLatestMessage() != null && getDatas().get(i - 1).getLatestMessage() != null) {
                    if (conv.getLatestMessage().getCreateTime() > getDatas().get(i - 1).getLatestMessage().getCreateTime()) {
                        newCount = i - 1;
                    } else {
                        newCount = i;
                        break;
                    }
                } else {
                    newCount = i;
                }
            }
            LogUtil.e(conv.getTitle());
            getDatas().add(newCount, conv);
        }
        mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
    }

    //置顶会话
    public void setConvTop(Conversation conversation) {
        int count = 0;
        //遍历原有的会话,得到有几个会话是置顶的
        for (Conversation conv : getDatas()) {
            if (!TextUtils.isEmpty(conv.getExtra())) {
                count++;
            }
        }
        conversation.updateConversationExtra(count + "");
        getDatas().remove(conversation);
        getDatas().add(count, conversation);
        mUIHandler.removeMessages(REFRESH_CONVERSATION_LIST);
        mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
    }

    List<Conversation> topConv = new ArrayList<>();
    List<Conversation> forCurrent = new ArrayList<>();

    //取消会话置顶
    public void setCancelConvTop(Conversation conversation) {
        forCurrent.clear();
        topConv.clear();
        int i = 0;
        for (Conversation oldConv : getDatas()) {
            //在原来的会话中找到取消置顶的这个,添加到待删除中
            if (oldConv.getId().equals(conversation.getId())) {
                oldConv.updateConversationExtra("");
                break;
            }
        }
        //全部会话排序
        SortConvList sortConvList = new SortConvList();
        Collections.sort(getDatas(), sortConvList);

        //遍历会话找到原来设置置顶的
        for (Conversation con : getDatas()) {
            if (!TextUtils.isEmpty(con.getExtra())) {
                forCurrent.add(con);
            }
        }
        topConv.addAll(forCurrent);
        SharePreferenceManager.setCancelTopSize(topConv.size());
        getDatas().removeAll(forCurrent);
        if (topConv != null && topConv.size() > 0) {
            SortTopConvList top = new SortTopConvList();
            Collections.sort(topConv, top);
            for (Conversation conv : topConv) {
                getDatas().add(i, conv);
                i++;
            }
        }
        notifyDataSetChanged();
    }

    public void addNewConversation(Conversation conv) {
        Log.d("FriendAdapter", "新增一个会话:");
        getDatas().add(0, conv);
        if (getDatas().size() > 0) {
//            mConversationListView.setNullConversation(true);
        } else {
//            mConversationListView.setNullConversation(false);
        }
        notifyDataSetChanged();
    }

    class ViewHolder extends BaseRecyclerViewHolder<Conversation> {

        public ViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        public void onBindData(Conversation data, int position) {
            ImageView avatarView = itemView.findViewById(R.id.iv_avatar);
            TextView nickNameView = itemView.findViewById(R.id.tv_nickname);
            TextView numberView = itemView.findViewById(R.id.new_msg_number);
            TextView contentView = itemView.findViewById(R.id.tv_content);
            int unReadCount = data.getUnReadMsgCnt();
            if (unReadCount != 0) {
                numberView.setVisibility(View.VISIBLE);
                numberView.setText(unReadCount + "");
            } else {
                numberView.setVisibility(View.GONE);
            }
            TextView timeView = itemView.findViewById(R.id.tv_time);
            if (data.getType() == ConversationType.group) {
                PicUtils.loadAvatarByGroup(data.getAvatarFile(), avatarView);
            } else {
                PicUtils.loadAvatar(data.getAvatarFile(), avatarView);
            }
            nickNameView.setText(data.getTitle());
            Message lastMessage = data.getLatestMessage();
            if (lastMessage != null) {
                ChatMessageEntity entity = JSON.parseObject(data.getLatestMessage().toJson(), ChatMessageEntity.class);
                contentView.setText(entity.getContent().getText());
                timeView.setText(TimeUtil.getDateMDHMS(data.getLatestMessage().getCreateTime()));
            }
            itemView.setSelected(selectConv.contains(data));
            if (pickModel == PICK_MODEL_MORE) {
                itemView.findViewById(R.id.cl_content).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (pickModel == PICK_MODEL_MORE) {
                            if (selectConv.contains(data)) {
                                selectConv.remove(data);
                                notifyDataSetChanged();
                            } else {
                                selectConv.add(data);
                                notifyDataSetChanged();
                            }
                            LiveEventBus.get(LiveDataBusConstant.UPDATE_SHARE_MEMBERS, String.class).post("");
                        }
                    }
                });
            } else {

                itemView.findViewById(R.id.cl_content).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getRvitemClickListener().onItemClick(itemView, position, data);
                    }
                });
            }

            if (pickModel == PICK_MODEL_SINGLE) {
                setVisibility(R.id.iv_pick, false);
            } else if (pickModel == PICK_MODEL_MORE) {
                setVisibility(R.id.iv_pick, true);
            } else {
                setVisibility(R.id.iv_pick, false);
            }
            String draft = mDraftMap.get(data.getId());
            //如果会话草稿为空,显示最后一条消息
            if (TextUtils.isEmpty(draft)) {
                Message lastMsg = data.getLatestMessage();
                if (lastMsg != null) {
                    TimeFormat timeFormat = new TimeFormat(context, lastMsg.getCreateTime());
                    //会话界面时间
                    timeView.setText(timeFormat.getTime());
                    String contentStr = "";
                    switch (lastMsg.getContentType()) {
                        case image:
                            contentStr = context.getString(R.string.type_picture);
                            break;
                        case voice:
                            contentStr = context.getString(R.string.type_voice);
                            break;
                        case location:
                            contentStr = context.getString(R.string.type_location);
                            break;
                        case file:
                            String extra = lastMsg.getContent().getStringExtra("video");
                            if (!TextUtils.isEmpty(extra)) {
                                contentStr = context.getString(R.string.type_smallvideo);
                            } else {
                                contentStr = context.getString(R.string.type_file);
                            }
                            break;
                        case video:
                            contentStr = context.getString(R.string.type_video);
                            break;
                        case eventNotification:
                            contentStr = context.getString(R.string.group_notification);
                            break;
                        case custom:
                            CustomContent customContent = (CustomContent) lastMsg.getContent();
                            Boolean isBlackListHint = customContent.getBooleanValue("blackList");
                            String sendScore = customContent.getStringExtra("sendScore");
                            String sendCoupon = customContent.getStringExtra("sendCoupon");
                            if (isBlackListHint != null && isBlackListHint) {
                                contentStr = context.getString(R.string.jmui_server_803008);
                            } else if (!TextUtils.isEmpty(sendScore)) {
                                contentStr = context.getString(R.string.type_custom_score);
                            } else if (!TextUtils.isEmpty(sendCoupon)) {
                                contentStr = context.getString(R.string.type_custom_coupon);
                            }
                            break;
                        case prompt:
                            contentStr = ((PromptContent) lastMsg.getContent()).getPromptText();
                            break;
                        default:
                            contentStr = ((TextContent) lastMsg.getContent()).getText();
                            break;
                    }

//                    if (lastMsg.getStatus() == MessageStatus.send_fail) {
//                        convListSendFail.setVisibility(View.VISIBLE);
//                    }else {
//                        convListSendFail.setVisibility(View.GONE);
//                    }

                    MessageContent msgContent = lastMsg.getContent();
                    Boolean isRead = msgContent.getBooleanExtra("isRead");
                    Boolean isReadAtAll = msgContent.getBooleanExtra("isReadAtAll");
                    if (lastMsg.isAtMe()) {
                        if (null != isRead && isRead) {
                            mArray.delete(position);
                            mAtConvMap.remove(data);
                        } else {
                            mArray.put(position, true);
                        }
                    }
                    if (lastMsg.isAtAll()) {
                        if (null != isReadAtAll && isReadAtAll) {
                            mAtAll.delete(position);
                            mAtAllConv.remove(data);
                        } else {
                            mAtAll.put(position, true);
                        }

                    }
                    long gid = 0;
                    if (data.getType().equals(ConversationType.group)) {
                        gid = Long.parseLong(data.getTargetId());
                    }

                    if (mAtAll.get(position) && FlyApplication.isAtall.get(gid) != null && FlyApplication.isAtall.get(gid)) {
                        contentStr = "[@所有人] " + contentStr;
                        SpannableStringBuilder builder = new SpannableStringBuilder(contentStr);
                        builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        contentView.setText(builder);
                    } else if (mArray.get(position) && FlyApplication.isAtMe.get(gid) != null && FlyApplication.isAtMe.get(gid)) {
                        //有人@我 文字提示
                        contentStr = context.getString(R.string.somebody_at_me) + contentStr;
                        SpannableStringBuilder builder = new SpannableStringBuilder(contentStr);
                        builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        contentView.setText(builder);
                    } else {
                        if (lastMsg.getTargetType() == ConversationType.group && !contentStr.equals("[群成员变动]")) {
                            UserInfo info = lastMsg.getFromUser();
                            String fromName = info.getDisplayName();
                            if (FlyApplication.isAtall.get(gid) != null && FlyApplication.isAtall.get(gid)) {
                                contentView.setText("[@所有人] " + fromName + ": " + contentStr);
                            } else if (FlyApplication.isAtMe.get(gid) != null && FlyApplication.isAtMe.get(gid)) {
                                contentView.setText("[有人@我] " + fromName + ": " + contentStr);
                                //如果content是撤回的那么就不显示最后一条消息的发起人名字了
                            } else if (msgContent.getContentType() == ContentType.prompt) {
                                contentView.setText(contentStr);
                            } else if (info.getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                                contentView.setText(contentStr);
                            } else {
                                contentView.setText(fromName + ": " + contentStr);
                            }
                        } else {
                            if (FlyApplication.isAtall.get(gid) != null && FlyApplication.isAtall.get(gid)) {
                                contentView.setText("[@所有人] " + contentStr);
                            } else if (FlyApplication.isAtMe.get(gid) != null && FlyApplication.isAtMe.get(gid)) {
                                contentView.setText("[有人@我] " + contentStr);
                            } else {
                                if (lastMsg.getUnreceiptCnt() == 0) {
                                    if (lastMsg.getTargetType().equals(ConversationType.single) &&
                                            lastMsg.getDirect().equals(MessageDirect.send) &&
                                            !lastMsg.getContentType().equals(ContentType.prompt) &&
                                            //排除自己给自己发送消息
                                            !((UserInfo) lastMsg.getTargetInfo()).getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                                        if (lastMsg.getStatus() == MessageStatus.send_fail) {
                                            contentView.setText(contentStr);
                                        } else {
                                            contentView.setText("[已读]" + contentStr);
                                        }
                                    } else {
                                        contentView.setText(contentStr);
                                    }
                                } else {
                                    if (lastMsg.getTargetType().equals(ConversationType.single) &&
                                            lastMsg.getDirect().equals(MessageDirect.send) &&
                                            !lastMsg.getContentType().equals(ContentType.prompt) &&
                                            !((UserInfo) lastMsg.getTargetInfo()).getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                                        contentStr = "[未读]" + contentStr;
                                        SpannableStringBuilder builder = new SpannableStringBuilder(contentStr);
                                        builder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.line_normal)),
                                                0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        contentView.setText(builder);
                                    } else {
                                        contentView.setText(contentStr);
                                    }

                                }
                            }
                        }
                    }
                } else {
                    if (data.getLastMsgDate() == 0) {
                        //会话列表时间展示的是最后一条会话,那么如果最后一条消息是空的话就不显示
                        timeView.setText("");
                        contentView.setText("");
                    } else {
                        TimeFormat timeFormat = new TimeFormat(context, data.getLastMsgDate());
                        timeView.setText(timeFormat.getTime());
                        contentView.setText("");
                    }
                }
            } else {
                draft = context.getString(R.string.draft) + draft;
                SpannableStringBuilder builder = new SpannableStringBuilder(draft);
                builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                contentView.setText(builder);
            }

        }
    }

    public void sortConvList() {
        forCurrent.clear();
        topConv.clear();
        int i = 0;
        SortConvList sortConvList = new SortConvList();
        Collections.sort(getDatas(), sortConvList);
        for (Conversation con : getDatas()) {
            if (!TextUtils.isEmpty(con.getExtra())) {
                forCurrent.add(con);
            }
        }
        topConv.addAll(forCurrent);
        getDatas().removeAll(forCurrent);
        if (topConv != null && topConv.size() > 0) {
            SortTopConvList top = new SortTopConvList();
            Collections.sort(topConv, top);
            for (Conversation conv : topConv) {
                getDatas().add(i, conv);
                i++;
            }
        }
        notifyDataSetChanged();
    }

    private static class UIHandler extends Handler {

        private final WeakReference<ShareFriendAdapter> mAdapter;

        public UIHandler(ShareFriendAdapter adapter) {
            mAdapter = new WeakReference<>(adapter);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            ShareFriendAdapter adapter = mAdapter.get();
            if (adapter != null) {
                switch (msg.what) {
                    case REFRESH_CONVERSATION_LIST:
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }

}
